import sys
import os
import re
import amara
from brightcontent.core.store import COMMON_PREFIXES, ATOM10_NS
from brightcontent.util import fixup_namespaces
from amara.binderytools import quick_xml_scan

def id_to_fname(id_):
    return re.sub('\W', '_', id_)
    #return '-'.join(id_.split('/')[-4:])
    #return id.replace(os.path.sep, '-')

input_file_or_url = sys.argv[1]
try:
    output_dir = sys.argv[2]
except IndexError:
    output_dir = '/tmp/atomstore'

try:
    os.makedirs(output_dir)
except OSError:
    pass

doc = amara.parse(input_file_or_url, prefixes=COMMON_PREFIXES)
envelope = amara.create_document(u"atom:feed", ns=ATOM10_NS)
for nonentry in doc.feed.xml_xpath(u'*[not(self::atom:entry)]'):
    envelope.feed.xml_append(nonentry)

f = open(os.path.join(output_dir, 'envelope.xml'), 'w')
fixup_namespaces(envelope)
f.write(envelope.xml(indent=u"yes"))
f.close()
for entry in doc.feed.entry:
    updated = amara.binderytools.parse_isodate(unicode(entry.updated))
    subdir = str(updated.date())
    full_path = os.path.join(output_dir, subdir)
    if not os.path.isdir(full_path):
        os.mkdir(full_path)
    fname = id_to_fname(unicode(entry.id))
    print subdir, fname
    f = open(os.path.join(output_dir, subdir, fname), 'w')
    f.write(entry.xml())
    f.close()

